﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PersonalWebSite.Common
{
    /// <summary>
    /// Defines the Cache Utility Class
    /// </summary>
    public class Cache
    {
        #region Variables
        private static readonly TimeSpan defaultCacheDuration = TimeSpan.FromHours(8);
        #endregion

        public static T CacheItem<T>(string cacheKey, Func<T> getterMethod)
        {
            return CacheItem<T>(cacheKey, getterMethod, defaultCacheDuration, null, null);
        }

        public static T CacheItem<T>(string cacheKey, Func<T> getterMethod, TimeSpan cacheDuration)
        {
            return CacheItem<T>(cacheKey, getterMethod, cacheDuration, null, null);
        }

        public static T CacheItem<T>(string cacheKey, Func<T> getterMethod, System.Web.Caching.CacheDependency cacheDependecy, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
        {
            return CacheItem<T>(cacheKey, getterMethod, System.Web.Caching.Cache.NoSlidingExpiration, cacheDependecy, onRemoveCallback);
        }

        public static T CacheItem<T>(string cacheKey, Func<T> getterMethod, TimeSpan cacheDuration, System.Web.Caching.CacheDependency cacheDependecy, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
        {
            if (HttpContext.Current == null)
                return getterMethod();

            var cachedObject = HttpContext.Current.Cache.Get(cacheKey);
            if (cachedObject != null)
                return (T)cachedObject;

            cachedObject = getterMethod();
            if (cachedObject == null)
                return (T)cachedObject;
            HttpContext.Current.Cache.Add(cacheKey, cachedObject, cacheDependecy, DateTime.Now.Add(defaultCacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, onRemoveCallback);

            return (T)cachedObject;
        }

        public static void RemoveItem(string cacheKey)
        {
            HttpContext.Current.Cache.Remove(cacheKey);
        }
    }
}